package com.wtb.thread;

import java.util.HashMap;
import java.util.concurrent.BlockingQueue;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.tencent.weibo.api.Statuses_API;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.WeiBoConst;
import com.wtb.domain.Config;
import com.wtb.domain.DataCache;
import com.wtb.pub.WtbException;
import com.wtb.qq.domain.QqOauth;
import com.wtb.rr.domain.RrOauth;
import com.wtb.utils.MessageUtils;

public class QqReadThread implements Runnable{
	private static final Log log = LogFactory.getLog(QqReadThread.class);
	private BlockingQueue<RrOauth> rrQueue;   							//人人状态发送队列
	private BlockingQueue<QqOauth> traver_qqQueue;						//qq微博遍历队列
	private Statuses_API statuses_API = new Statuses_API();				//qq微博时间线API
	private OAuth oauth = new OAuth(Config.QQ_APP_KEY,Config.QQ_APP_SECRET,"");
	private String broadcast_str = null;								//返回的时间线内容字符串
	private QqOauth qqOauth = null;		
	private String qqlastTime;											//最后一次获取并发送的时间
	private String lastStatusTime;										//微博的最后发送时间
	private JSONObject broadcast_json_data;								//json_data
	private JSONObject broadcast_json;									//获取第一条微博
	private String image_url; 											//图片地址
	private JSONArray images;											//图片地址数组
	private HashMap<String , RrOauth> rr_map;
	public QqReadThread( BlockingQueue<RrOauth> rrQueue,BlockingQueue<QqOauth> traver_qqQueue) {
		this.rrQueue = rrQueue;
		this.traver_qqQueue = traver_qqQueue;
	}
	public void run() {
		log.info("QQ读线程已启动");
		while (true) {
			log.debug("*********"+Thread.currentThread().getName()+"在工作！*************");
			try {
				qqOauth = traver_qqQueue.take();
				//初始化API请求参数
				oauth.setOauth_token(qqOauth.getOauth_token());
				oauth.setOauth_token_secret(qqOauth.getOauth_token_secrete());
				broadcast_str = statuses_API.broadcast_timeline(oauth, WeiBoConst.ResultType.ResultType_Json, "0", "0", "2", "0", "1", "0", "0");
			} catch (Exception e) {
				log.error("获取时间线失败：", e);
				throw new WtbException("获取时间线失败", e);
			}
			if (broadcast_str != null) {
				praseResult(broadcast_str);
			}
		}
	}
	/**
	 * 解析返回字符串JSON
	 * @param broadcast_str
	 */
	private void praseResult(String resultString){
		broadcast_json_data = (JSONObject) JSONObject.fromObject(resultString).getJSONObject("data");
		if (broadcast_json_data.toString().equals("null")) {
			return;
		}
		broadcast_json = (JSONObject) broadcast_json_data.getJSONArray("info").get(0);
		log.debug("微博:"+broadcast_json);
	    lastStatusTime = broadcast_json.getString("timestamp");
	    for (int i = 0; i < Config.QQ_FROM.length; i++) {
			if (broadcast_json.getString("from").equals(Config.QQ_FROM[i])) {
				return;
			}
		}
	    qqlastTime = DataCache.synQqTime(qqOauth.getUni()); 
		if (Long.valueOf(lastStatusTime) > Long.valueOf(qqlastTime) ) {
			putToQueue(broadcast_json);
		}
	}
	
	/**
	 * 生成人人状态发送队列
	 * @param qqOauth
	 * @param data
	 */
	@SuppressWarnings("unchecked")
	private void putToQueue(JSONObject data) {
		rr_map = DataCache.synRrMap();
		if (!rr_map.containsKey(qqOauth.getRef())) { //已被其他线程删除
			return;
		}
		RrOauth rrOauth = (RrOauth) rr_map.get(qqOauth.getRef());
		// 如果为@某人的微博 不转发
		String mes = data.getString("origtext");
		if (MessageUtils.cotainString(mes, "@,分享,#")) {
			return;
		}
		//表情过滤后为空 不转发
		String mess = MessageUtils.qq2rrExpression(mes);
		if (mess == null || "".equals(mess)) {
			return;
		}
		//以“-”结尾 不转发
		if (mes.lastIndexOf("-")==mes.length()-1) {
			return;
		}
		//带视频或音乐的微博 不转发
		if (!data.get("music").toString().equals("null") || !data.get("video").toString().equals("null")) {
			return;
		}
		//带图片的微博 处理
		if (!data.get("image").toString().equals("null")) {
			if (!data.getJSONArray("image").isEmpty()) {
				images = data.getJSONArray("image");
				image_url = images.get(0)+"/2000.jpg";
				rrOauth.setImageUrl(image_url);
			}
		}
		rrOauth.setMessage(mess);
		rrOauth.setLastTime(data.getString("timestamp"));
		try {
			log.debug("已加入人人状态发送队列");
			rrQueue.put(rrOauth);
		} catch (InterruptedException e) {
			log.error("放入微博队列失败：", e);
			throw new WtbException("放入微博队列失败", e);
		}
	}
	
}
